package cmd

import (
	"bytes"
	"docker-api/internal/model"
	"fmt"
	"os/exec"
)

// FetchCurrentVersionInfo 获取当前系统的版本信息
func FetchCurrentVersionInfo() (*model.DockerVersion, error) {
	// 获取 Docker 信息
	dockerInfo, err := GetVersion()
	if err != nil {
		return nil, fmt.Errorf("当前系统未安装 Docker 或 Docker 服务未启动: %w", err)
	}

	// 获取系统信息
	systemInfo, err := GetSystemInfo()
	osVersion := "未知"
	if err == nil && systemInfo != nil {
		if systemInfo.Version != "" {
			osVersion = fmt.Sprintf("%s %s", systemInfo.OS, systemInfo.Version)
		} else {
			osVersion = systemInfo.OS
		}
	}

	// 获取 Compose 信息
	composeInfo, err := GetComposeVersion()
	composeVersion := "未安装"
	if err == nil && composeInfo != nil {
		composeVersion = composeInfo.Version
	}

	return &model.DockerVersion{
		DockerVersion:  dockerInfo.Version,
		OsVersion:      osVersion,
		ComposeVersion: composeVersion,
	}, nil
}

// ExecuteSystemCommand 执行系统命令
func ExecuteSystemCommand(cmd *exec.Cmd) (string, error) {
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		return "", fmt.Errorf("命令执行失败: %v, stderr: %s", err, stderr.String())
	}

	return out.String(), nil
}

// ExecuteSystemCommandRaw 执行系统命令并返回原始字节
func ExecuteSystemCommandRaw(cmd *exec.Cmd) ([]byte, error) {
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("命令执行失败: %v, stderr: %s", err, stderr.String())
	}

	return out.Bytes(), nil
}

// ExecuteCommand 执行命令并返回输出
func ExecuteCommand(cmd *exec.Cmd) (string, error) {
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		return "", fmt.Errorf("命令执行失败: %v, stderr: %s", err, stderr.String())
	}

	return out.String(), nil
}
